import 'package:flutter/material.dart';
/* 
PageView 意思是充满一页的组件
children中的每个元素都占据一个单独的页面

scrollDirection               水平方向 垂直方向         Axis.horizonta / Axis.vertical 
children                      配置子元素
allowImplicitScrolling        缓存当前页面的前后两页
onPageChanged                 page改变的时候触发


*/

class PageViewPage extends StatefulWidget {
  const PageViewPage({super.key});

  @override
  State<PageViewPage> createState() => _PageViewPageState();
}

/* 
PageView和PageView.builder的分别应用
*/

/* 
class _PageViewPageState extends State<PageViewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PageView'),
      ),
      body: PageView(
        scrollDirection: Axis.vertical, // 滑动方向为垂直方向
        children: [
          Center(
            child: Text(
              "1",
              style: Theme.of(context).textTheme.bodyLarge,
            ),
          ),
          Center(
            child: Text(
              "2",
              style: Theme.of(context).textTheme.bodyLarge,
            ),
          ),
          Center(
            child: Text(
              "3",
              style: Theme.of(context).textTheme.bodyLarge,
            ),
          ),
          Center(
            child: Text(
              "4",
              style: Theme.of(context).textTheme.bodyLarge,
            ),
          ),
        ],
      ),
    );
  }
} 
*/

class _PageViewPageState extends State<PageViewPage> {
  final List<Widget> _list = [];

  @override
  void initState() {
    super.initState();
    for (var i = 0; i < 10; i++) {
      _list.add(MyPage(text: "${i+1}"));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PageView'),
      ),
      body: PageView(
        scrollDirection: Axis.vertical, // 滑动方向为垂直方向
        children: _list,
        onPageChanged: (value) {
          // 参数value 是每项的索引  下面if判断是提前两项开始加载下一页
          if (value + 2 == _list.length) {
            setState(() {
              for (var i = 0; i < 10; i++) {
                _list.add(MyPage(text: '${i + 1}'));
              }
            });
          }
        },
      ),
    );
  }
}

class MyPage extends StatefulWidget {
  final String text;
  const MyPage({super.key, required this.text});

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        widget.text,
        style: Theme.of(context).textTheme.headlineLarge,
      ),
    );
  }
}
